import { useState, useEffect } from "react"
import Tree from "./Tree"
export default () => {
  let [data, setData] = useState([])

  useEffect(() => {
    fetch('/citydata.json').then(res => res.json()).then(res => {
      setData(recursionConfigProp(res))
    })
  }, [])

  // 当数据请求过来后我们要递归式给每一个数据加一个属性，用来控制是否展开功能
  let recursionConfigProp = (data: any, type?: any, id?: any) => {
    // show = true 则展开，false 折叠
    return data.map((item: any) => {
      if (type === 'reset') {
        if (item.value === id) {
          item.show = !item.show;
        }
      } else if (typeof item.show !== 'boolean') {
        item.show = false
      }
      // 递归式自己调用自己
      if (item.children) {
        if (type === 'reset') {
          recursionConfigProp(item.children, type, id)
        } else {
          recursionConfigProp(item.children)
        }
      }
      return item;
    })
  }

  // 获取到子组件传递过来的数据
  let setShow = (son: any) => {
    setData(recursionConfigProp(data, 'reset', son.value))
  }

  return <>
    <Tree data={data} setShow={setShow}></Tree>
  </>
}